<template>
    <AuthWrapper>
        <template #title>Reset Password</template>
        <template #subtitle>更新您账号的密码</template>

        <div class="mb-2">
            <input type="radio" class="btn-check" name="resetMode" id="passwordMode" value="password"
                v-model="form.mode" autocomplete="off" checked />
            <label class="btn" for="passwordMode">旧密码验证</label>

            <input type="radio" class="btn-check" name="resetMode" id="emailMode" value="email" v-model="form.mode"
                autocomplete="off" />
            <label class="btn" for="emailMode">邮箱验证码</label>
        </div>

        <div class="mb-1">
            <FloatingInput v-model="form.username" label="用户名" type="text" required />
        </div>

        <div v-if="form.mode === 'password'" class="mb-1">
            <FloatingInput v-model="form.old_password" label="旧密码" type="password" required />
        </div>

        <div v-if="form.mode === 'email'" class="mb-2">
            <div class="input-group mb-2">
                <div class="form-floating">
                    <input id="verifyCode" v-model="form.verify_code" type="text" class="form-control" placeholder="验证码"
                        required />
                    <label for="verifyCode">验证码</label>
                </div>
                <button class="btn btn-outline-secondary" type="button" :disabled="countdown > 0 || sendLoading"
                    @click="handleSendCode">
                    <span v-if="sendLoading" class="spinner-border spinner-border-sm me-2" role="status"
                        aria-hidden="true"></span>
                    {{ countdown > 0 ? `${countdown}s后重试` : '发送验证码' }}
                </button>
            </div>
        </div>

        <div class="mb-3">
            <FloatingInput v-model="form.new_password" label="新密码" type="password" required />
        </div>

        <button class="btn btn-primary w-100" :disabled="resetLoading" @click="handleReset">
            <span v-if="resetLoading" class="spinner-border spinner-border-sm me-1"></span>确认修改
        </button>
    </AuthWrapper>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { useToast } from '../composables/useToast';
import { useApi } from '../composables/useApi';

import AuthWrapper from '../components/AuthWrapper.vue';
import FloatingInput from '../components/FloatingInput.vue';

const { success, error, warning } = useToast();

// 表单数据
const form = reactive({
    username: '',
    old_password: '',
    new_password: '',
    verify_code: '',
    mode: 'password' // 默认使用旧密码验证
});

// 倒计时
const countdown = ref(0);
let timer = null;

// ⏱ 启动倒计时
const startCountdown = () => {
    countdown.value = 60;
    timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) clearInterval(timer);
    }, 1000);
};

// ✉️ 发送验证码请求
const {
    fetchData: sendCode,
    loading: sendLoading,
    result: codeResult
} = useApi({
    url: '/auth/verify/code',
    method: 'post',
    manual: true,
    toast: true
});

const handleSendCode = async () => {
    if (!form.username) {
        warning('请先输入用户名');
        return;
    }
    try {
        await sendCode({
            data: {
                mode: 'reset',
                username: form.username
            }
        });
        const res = codeResult.value;
        if (res.code === 0) {
            success(res?.msg || '验证码发送成功');
        } else {
            warning(res?.msg || '验证码发送失败');
        }
        startCountdown();
    } catch (e) {
        error('验证码发送失败');
    }
};

// 🔐 重置密码请求
const {
    fetchData: resetPassword,
    loading: resetLoading,
    result: resetResult
} = useApi({
    url: '/auth/reset/password',
    method: 'post',
    manual: true,
    toast: true
});

// 新增：密码强度校验函数
const validatePassword = password => {
    // 至少8位，包含字母和数字
    const regex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,}$/;
    return regex.test(password);
};

const handleReset = async () => {
    if (resetLoading.value) return; // 防止重复提交

    // 校验用户名
    if (!form.username) {
        warning('请填写用户名');
        return;
    }

    // 根据不同模式校验相应字段
    if (form.mode === 'password') {
        if (!form.old_password) {
            warning('请填写旧密码');
            return;
        }
    } else if (form.mode === 'email') {
        if (!form.verify_code) {
            warning('请填写验证码');
            return;
        }
    }

    // 校验新密码
    if (!form.new_password) {
        warning('请填写新密码');
        return;
    }

    // 校验新密码强度
    if (!validatePassword(form.new_password)) {
        warning('密码至少8位，包含字母和数字');
        return;
    }

    try {
        // 准备提交数据
        const submitData = {
            username: form.username,
            new_password: form.new_password,
            mode: form.mode
        };

        // 根据不同模式添加相应字段
        if (form.mode === 'password') {
            submitData.old_password = form.old_password;
        } else if (form.mode === 'email') {
            submitData.verify_code = form.verify_code;
        }

        await resetPassword({
            data: submitData
        });
        const res = resetResult.value;
        if (res.code === 0) {
            success(res?.msg || '修改密码成功');
        } else {
            error(res?.msg || '修改密码失败');
        }
    } catch (err) {
        // 错误已由 useApi toast 处理
        console.log(err);
    }
};
</script>

<style scoped>
.container {
    /* background: #fff; */
    border-radius: 8px;
    box-shadow: 0 0 12px rgba(0, 0, 0, 0.05);
}
</style>
